#
# \file
# \brief
# \author Marco Antonio Pinto Orellana
#
# -------------------------------------------------------------------------
#
# Copyright (C) 2012  (see AUTHORS file for a list of contributors)
# http://opentonitruum.sourceforge.net
#
# This file is part of OpenTonitruum - a simulator/library of signal trans-
# mission, modulation and processing in a wireless environment.
#
# OpenTonitruum is free software: you can redistribute it and/or modify it 
# under the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at 
# your option) any later version.
#
# OpenTonitruum is distributed in the hope that it will be useful, but WITH-
# OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with OpenTonitruum.  If not, see <http://www.gnu.org/licenses/>.
#
# -------------------------------------------------------------------------
#
from SimPy.Simulation import *
from DataStructure import *

class TransmissionSystem(object):
	def __init__(self):
		pass
	
	def encode(self, block):
		return block
	
	def decode(self, block):
		return block

		
class PhysicalLayer(Process):
	def __init__(self, encoder = TransmissionSystem(), transmittingTimeByBit = 1):
		Process.__init__(self)
		self._mediumResource = Resource(1)
		self._current = None
		self._correctBit = None
		self._correctBits = []
		self.parallelBitNumber = 4
		self._transmitting = False
		self._transmittingTimeByBit = transmittingTimeByBit
		self._encoder = encoder
		self.transmitionEnd = SimEvent("")
	
	def transmit(self, target, bit):
		self._correctBits.append(bit)
		if len(self._correctBits) == self.parallelBitNumber:
			self._transmitting = True
	
	def listen(self):
		#TODO: Add noise errors arose from Transreceiver
		return self._encoder.decode(self._current)
	
	def run(self):
		while True:
			yield waituntil, self, lambda: self._transmitting
			yield request, self, self._mediumResource
			#TODO: Add noise errors arose from Transreceiver
			self._current = self._encoder.encode(self._correctBits)
			yield hold, self, self._transmittingTimeByBit * len(self._correctBits)
			self._transmitting = False
			self._correctBits = []
			yield release, self, self._mediumResource
			self.transmitionEnd.signal()

